package api;


import model.User;
import model.UserDao;
import view.HtmlGenerator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//注册新用户
public class RegisterServlet extends HttpServlet {
    //浏览器是通过POST方法将注册信息提交给服务器的
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //1.获取前端提交的用户名和密码，并且检验是否合法
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        if(name == null ||  password == null || "".equals(name) || "".equals(password)){
            //用户提交的数据有误
            //返回一个错误页面
            String html =  HtmlGenerator.getMessagePage("用户名或密码为空","register.html");
            resp.getWriter().write(html);
            return;
        }

        //2.将信息拿到数据库中检索，判断是该用户名是否已经存在
        UserDao userDao = new UserDao();
        User userExists = userDao.selectByName(name);
        if(userExists != null){
            //说明该用户名已经存在，需要换一个用户名
            String html = HtmlGenerator.getMessagePage("用户名重复，请换一个用户名！","register.html");
            resp.getWriter().write(html);
            return;
        }

        //3.构造一个User对象，将注册的用户信息放到数据库中
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        userDao.add(user);

        //4.返回一个结果页面，提示用户注册成功
        String html = HtmlGenerator.getMessagePage("注册成功！点击跳转到登录页面","login.html");
        resp.getWriter().write(html);
    }
}
